package lumingweihua.future.cn.lumingweihua.home.cheyuan;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;

import java.util.ArrayList;
import java.util.List;

import lumingweihua.future.cn.baselibgxh.adapter.BaseViewHolder;
import lumingweihua.future.cn.baselibgxh.adapter.CommonAdapter;
import lumingweihua.future.cn.baselibgxh.base.BaseActivity;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialog;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialogEntity;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.NetworkManager;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.CommonUtils;
import lumingweihua.future.cn.baselibgxh.utils.Constant;
import lumingweihua.future.cn.lumingweihua.MainActivity;
import lumingweihua.future.cn.lumingweihua.R;
import lumingweihua.future.cn.lumingweihua.home.domain.CheyuanData;
import lumingweihua.future.cn.lumingweihua.home.domain.HuoyuanDetailData;
import lumingweihua.future.cn.lumingweihua.home.domain.LoadingPointData;
import lumingweihua.future.cn.lumingweihua.home.domain.UnloadData;
import lumingweihua.future.cn.lumingweihua.person.domain.PersonData;
import lumingweihua.future.cn.lumingweihua.release.ReleaseGoodsActivity;
import lumingweihua.future.cn.lumingweihua.ui.mine.MineCarActivity;
import lumingweihua.future.cn.lumingweihua.ui.mine.MineGoodsSourceActivity;
import lumingweihua.future.cn.lumingweihua.ui.order.OrderDetailActivity;

/**
 * Created by Administrator on 2018/3/3.
 */

public class HuoyuanDetailActivity extends BaseActivity {

    @Override
    protected void initView() {
        setContentView(R.layout.activity_huoyuan_detail);
        initTitleBar("货源详情", Constant.DEFAULT_LEFT_BACK, null);

        findViewById(R.id.bt_phone).setOnClickListener(this);
//        findViewById(R.id.bt_ok).setOnClickListener(this);
    }

    private boolean isMine;
    private HuoyuanDetailData huoyuanDetailData;

    @Override
    protected void initData() {
        isMine = getIntentExtra("isMine",true);

        requestData();
        requestPersonData(REQUEST_PERSON2);
    }

    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.bt_phone:
                CommonUtils.readyCall(context,huoyuanDetailData.getHot_line());
                break;
            case R.id.bt_ok:
                if(isMine){
                    if("2".equals(huoyuanDetailData.getGood_status())){
                        //2已通过 查看订单
                        startActivity(new Intent(context, OrderDetailActivity.class).putExtra("extra_id",huoyuanDetailData.getGood_num()));
                    }else if("3".equals(huoyuanDetailData.getGood_status())){
                        //3拒绝 修改货源信息
                        startActivity(new Intent(context, ReleaseGoodsActivity.class).putExtra("data",huoyuanDetailData));
                    }
                }else{
                    if(huoyuanDetailData.getIsself())
                        jumpToNextActivity(MineGoodsSourceActivity.class,false);
                    else{
                        //抢单
                        requestPersonData(REQUEST_PERSON);
                    }
                }
                break;
            case R.id.bt_title_right:
                new YesOrNoDialog(context, new YesOrNoDialogEntity("确定结束吗？\n结束后，货源将不在APP显示", "取消", "确定"),
                        new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                            @Override
                            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                switch (yesOrNoType) {
                                    case BtnOk:
                                        requestDel();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }).show();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 101 && resultCode == RESULT_OK){
            setResult(RESULT_OK);
            finish();
        }
    }

    /** 请求标识 **/
    private final int REQUEST_SET = 0;
    private final int REQUEST_DATA = 1;
    private final int REQUEST_DEL = 2;
    private final int REQUEST_PERSON = 4;
    private final int REQUEST_PERSON2 = 5;
    /**
     * 公共个人信息
     */
    private void requestPersonData(int reid) {
		showProgressBar(null);

        BeanRequest<PersonData, DefaultMamahaoServerError> req = new BeanRequest<>(
                context,
                "",
                this, PersonData.class);

        req.setParam("apiCode", "_userinfo_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, reid);
    }
    /**
     * 请求注册
     */
    private void requestData() {
        showProgressBar(null);

        BeanRequest<HuoyuanDetailData, DefaultMamahaoServerError> req = new BeanRequest<HuoyuanDetailData, DefaultMamahaoServerError>(
                context,
                "",
                this, HuoyuanDetailData.class);


        req.setParam("apiCode", isMine?"_usergoods_details_001":"_good_particulars_001");
        req.setParam("id", getIntentExtra("id"));
        req.setParam("userToken", MyApplication.getInstance().getUserToken());

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_DATA, new ReqTag.Builder().handleSimpleRes(true));
    }

    /**
     * 邀请司机
     */
    private void requestDel(){
        showProgressBar(null);

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context,"",this);

        req.setParam("apiCode", "_delete_goods_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());
        //传这个参数代表修改，没有代表新增地址
        req.setParam("id", getIntentExtra("id"));

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_DEL, new ReqTag.Builder().handleSimpleRes(true));
    }

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        // TODO Auto-generated method stub
        super.onResponseSuccess(tag, data);
        switch (tag.getReqId()) {
            case REQUEST_SET:
                // 设置成功
                new YesOrNoDialog(context, new YesOrNoDialogEntity("邀请消息已通过短信方式发送给车主，请耐心等待车主与您联系", null, "我知道啦"),
                        new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                            @Override
                            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                switch (yesOrNoType) {
                                    case BtnOk:
                                        setResult(RESULT_OK);
                                        finish();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }).show();
                break;
            case REQUEST_DATA:
                //
                huoyuanDetailData = (HuoyuanDetailData) data;
                setText(R.id.tv_num,huoyuanDetailData.getGood_num());
                setText(R.id.tv_start_address,huoyuanDetailData.getLoading());
                setText(R.id.tv_start_detail_address,huoyuanDetailData.getLoading_address());
                setText(R.id.tv_expert_course,huoyuanDetailData.getMileage());

                try {
                    DistanceFragment mapFragment = new DistanceFragment();
                    mapFragment.setDatas(huoyuanDetailData.getLat()
                            ,huoyuanDetailData.getLon()
                            ,huoyuanDetailData.getXiehuo().get(huoyuanDetailData.getXiehuo().size()-1).getLat()
                            ,huoyuanDetailData.getXiehuo().get(huoyuanDetailData.getXiehuo().size()-1).getLon()
                    );
                    getSupportFragmentManager().beginTransaction()
                            .add(R.id.fragment_container, mapFragment).commit();
                } catch (Exception e) {
                    // TODO: handle exception
                }


                setText(R.id.tv_time,huoyuanDetailData.getUse_time());
                setText(R.id.tv_goods_name,huoyuanDetailData.getType());
                setText(R.id.tv_goods_weight,huoyuanDetailData.getWeight()+"吨");
                setText(R.id.tv_unit_price,huoyuanDetailData.getUnit_price());
                setText(R.id.tv_total_price,huoyuanDetailData.getCost());
                setText(R.id.tv_count_type,huoyuanDetailData.getAccount_type());
                setText(R.id.tv_note,huoyuanDetailData.getNote(),"暂无备注");

                if(huoyuanDetailData.getXiehuo()!=null){
                    ListView listview = findViewById(R.id.listview);
                    listview.setAdapter(new CommonAdapter<UnloadData>(context,huoyuanDetailData.getXiehuo(),R.layout.item_loading_point) {
                        @Override
                        public void convert(BaseViewHolder holder, UnloadData itemData, int position, ViewGroup parent) {
                            holder.setText(R.id.tv_start_address,itemData.getUnload());
                            holder.setText(R.id.tv_start_detail_address,itemData.getUnload_address());
                        }
                    });
                }

                TextView bt_ok = findViewById(R.id.bt_ok);
                if(isMine){
                    if("1".equals(huoyuanDetailData.getGood_status())){
                        //1待审核
                        bt_ok.setVisibility(View.GONE);
                        findViewById(R.id.tv_count_time).setVisibility(View.VISIBLE);
                        setText(R.id.tv_count_time,"货源信息审核中，请耐心等待...");
                    }else if("2".equals(huoyuanDetailData.getGood_status())){
                        //2已通过
                        bt_ok.setText("查看订单");
                        bt_ok.setOnClickListener(this);
                        bt_title_right.setText("结束订单");
                        bt_title_right.setOnClickListener(this);
                    }else if("3".equals(huoyuanDetailData.getGood_status())){
                        //3拒绝
                        bt_ok.setText("修改货源信息");
                        findViewById(R.id.tv_count_time).setVisibility(View.VISIBLE);
                        setText(R.id.tv_count_time,"拒绝原因：\n"+huoyuanDetailData.getReject_reason());
                    }else{
                        //4结束;
                        bt_ok.setVisibility(View.GONE);
                        findViewById(R.id.tv_count_time).setVisibility(View.VISIBLE);
                        setText(R.id.tv_count_time,"该货源已结束抢单");
                    }
                }else{
                    if("1".equals(huoyuanDetailData.getIndent_type())){
                        //已发出邀请
                        bt_ok.setBackgroundColor(Color.parseColor("#cccccc"));
                    }else{
                        bt_ok.setOnClickListener(this);
                        if(huoyuanDetailData.getIsself())
                            bt_ok.setText("管理我的货源");
                    }
                }
                break;
            case REQUEST_DEL:
                showToast("结束成功");
                setResult(RESULT_OK);
                finish();
                break;
            case REQUEST_PERSON2:
                if(((PersonData)data)!=null){
                    if(((PersonData)data).getIsFinishDriverAuth() || ((PersonData)data).getIsFinishCarAuth())
                        setText(R.id.bt_phone,"拨打电话");
                }else{

                }
                break;
            case REQUEST_PERSON:
                PersonData personData = (PersonData)data;
            if(personData!=null && personData.getIsFinishCarAuth()){
                //完成认证
                new lumingweihua.future.cn.lumingweihua.home.dialog.YesOrNoDialog(context, new YesOrNoDialogEntity("您好，为了合作共赢互赢互利的原则，我公司规定：\n" +
                        "\n" +
                        "一：司机运输途中必须确保货物安全，保证货物无泄漏，无污染。 \n" +
                        "二：未按规定时间运送货物到达，逾期造成严重损失，由车上负责，不可抗拒因素除外。\n" +
                        "三：在运输途中出现交通事故，车上承担赔偿责任。  \n" +
                        "四：运输过程中货物灭失、短少、变质、被盗、交货不清等因素、车上应承担全部责任。\n" +
//                        "\n" +
                        "您必须同意以上合作规定，才能在本平台进行做单，谢谢支持！\n", "不同意", "同意"),
                        new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                            @Override
                            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                switch (yesOrNoType) {
                                    case BtnOk:
                                        //抢单
                                        startActivityForResult(new Intent(context,RobOrderActivity.class)
                                                        .putExtra("limitNum",huoyuanDetailData.getRemain_weight())
                                                        .putExtra("good_num",huoyuanDetailData.getGood_num())
                                                ,101);
//                                                requestSet();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }).show();
            }else{
                //去认证
                new YesOrNoDialog(context, new YesOrNoDialogEntity("完成车辆认证后，才能进行货源抢单", "暂不认证", "立即认证"),
                        new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                            @Override
                            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                switch (yesOrNoType) {
                                    case BtnOk:
                                        jumpToNextActivity(MineCarActivity.class,false);
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }).show();
            }
                    break;

            default:
                break;
        }
    }

    @Override
    protected void onResponseFailure(ReqTag tag, MamaHaoServerError error, AbstractRequest.MamaHaoError clientError) {
        super.onResponseFailure(tag, error, clientError);
    }
}
